<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-06-02
 * Time: 15:17
 */

namespace app\applet\controller;


use app\applet\BaseController;
use think\facade\Db;

/**
 * Class QuestionController
 * @package app\applet\controller
 */
class QuestionController extends BaseController
{
    /**
     * 获取题目
     */
    public function indexAction()
    {
        try {
            //1. 检测用户答题次数，是否超过限制
            $res = $this->app->questionService->checkAnswer($this->user);

            $data['process'] = $res;

            //2. 随机选出一道题目
            $question = $this->app->questionService->getRandQuestion();
            $data['question'] = $question;

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);

        } catch (\Exception $e) {
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * 答题
     * @return \think\response\Json
     */
    public function answerAction()
    {
        Db::startTrans();
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }
            $question = $this->app->questionService->getDetail($this->post['questionId']);

            //1. 检测用户答题次数，是否超过限制
            $this->app->questionService->checkAnswer($this->user);

            //2.记录
            $answer = $this->app->questionService->answer($this->user, $question, $this->post['answer']);

            if ($answer->credit > 0) {
                $remark = '回答"'.$answer->question->questionTitle.'",获取'.$answer->credit.'积分';

                $this->app->userCreditService->add($this->user, $answer->credit, $remark);
            }

            $data = [
                'isRight' => $answer->isRight,
                'credit' => $answer->credit,
            ];

            Db::commit();

            return json(['code' => 200, 'msg' => '答题成功', 'data'=> $data]);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }
}